package com.cn.controller.user;

import com.cn.entity.Order;
import com.cn.entity.User;
import com.cn.enums.ErrorMsg;
import com.cn.mapper.OrderMapper;
import com.cn.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * 用户订单控制器
 */
@RestController
@RequestMapping("user/order")
public class UserOrderController {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 创建订单（模拟购买）
     */
    @PostMapping("create")
    public Result createOrder(@RequestBody Order order, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.fail(ErrorMsg.COOKIE_ERROR);
        }

        // 生成订单号
        String orderNumber = "ORDER" + System.currentTimeMillis();
        
        // 设置订单信息
        order.setOrderNumber(orderNumber);
        order.setUserId(user.getId());
        order.setCreateTime(new Date());
        order.setOrderStatus((byte) 0);  // 0-待付款
        order.setPaymentStatus((byte) 0);  // 0-未支付
        
        // 插入订单
        int result = orderMapper.insert(order);
        if (result > 0) {
            return Result.success();
        }
        
        return Result.fail(ErrorMsg.SYSTEM_ERROR);
    }
    
    /**
     * 获取我的订单
     */
    @GetMapping("myOrders")
    public Result getMyOrders(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.success(new java.util.ArrayList<>());
        }
        
        List<Order> list = orderMapper.getMyOrder(user.getId());
        return Result.success(list);
    }
}
